package com.shr.xsunmvc.render;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shr.xsunmvc.DefaultValue;
import com.shr.xsunmvc.Xsun;
import com.shr.xsunmvc.XsunContext;

/**
 * JSP渲染器
 * @author sun haoran
 *
 */
public class JspRender implements Render{

	@Override
	public void render(String view, Writer writer) {
		String viewPath = this.getViewPath(view) ;
		
		HttpServletRequest request = XsunContext.me().getRequest().getRequest() ;
		HttpServletResponse response = XsunContext.me().getResponse().getResponse() ;
		
		try {
			request.getRequestDispatcher(viewPath).forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String getViewPath(String view) {
		Xsun xsun = Xsun.me() ;
		String viewPrefix = xsun.getConf(DefaultValue.VIEW_PREFIX_FIELD) ;
		String viewSuffix = xsun.getConf(DefaultValue.VIEW_SUFFIX_FIELD) ;
		if(viewPrefix == null || viewPrefix.length() == 0)
			viewPrefix = DefaultValue.VIEW_PREFIX ;
		if(viewSuffix == null || viewSuffix.length() == 0)
			viewSuffix = DefaultValue.VIEW_SUFFIX ;
		
		String viewPath = viewPrefix + view ;
		if(!viewPath.endsWith(viewSuffix))
			viewPath += DefaultValue.VIEW_SUFFIX ;
		
		return viewPath.replaceAll("[/]+", "/") ;
	}

}
